$(function () {
	   
    $("#jqGrid").jqGrid({
        url: baseURL + 'fund/list',
        datatype: "json",
        colModel: [
			{ label: 'ID', name: 'id', width: 0, key: true, hidden:true},
			{ label: '用户', name: 'phone', index: 'phone', width: 96 , sortable:false, formatter: function(value, options, row)
				{
					if(null == value || undefined == value) return "";
					
					return "<a href='tradeinfo.html?userId=" + row.userId + "'>" + value +  "</a>";
				}
			},
			{ label: 'IMU/锁定', name: 'money', sortable:false, width: 80 , formatter: function(value, options, row)
                {
                    return ((null == row.money || undefined == row.money) ? 0 : row.money) + "/" + ((null == row.lockMoney || undefined == row.lockMoney) ? 0 : row.lockMoney);
                }
            },
            { label: '易买宝/锁仓', name: 'bj', sortable:false, width: 80 , formatter: function(value, options, row)
                {
                    return ((null == row.bj || undefined == row.bj) ? 0 : row.bj) + "/" + ((null == row.lockbj || undefined == row.lockbj) ? 0 : row.lockbj);
                }
            },
            { label: '交易员', name: 'btc', sortable:false, width: 80 , formatter: function(value, options, row)
                {
                    return ((null == row.btc || undefined == row.btc) ? 0 : row.btc);
                }
            },
            { label: '智多星/锁仓', name: 'fcg', sortable:false, width: 80 , formatter: function(value, options, row)
                {
                    return ((null == row.fcg || undefined == row.fcg) ? 0 : row.fcg) + "/" + ((null == row.lockfcg || undefined == row.lockfcg) ? 0 : row.lockfcg);
                }
            },
            { label: '俱乐部/锁仓', name: 'hbc', sortable:false, width: 80 , formatter: function(value, options, row)
                {
            		if(null == value || undefined == value) return "未知";
            	
                	if(value < 10 ) return "非俱乐部会员";
                	if(value>=10 && value<200) return "白银卡";
                    if(value>=200 && value<500) return "黄金卡";
                    if(value>=500 && value<1000) return "钻石卡";
                    if(value>=1000 && value<2000) return "白金卡";
                    if(value>=2000) return "黑金卡";
                }
            },
            { label: 'KCT/锁仓', name: 'ico', sortable:false, width: 80 , formatter: function(value, options, row)
                {
                    return ((null == row.ico || undefined == row.ico) ? 0 : row.ico) + "/" + ((null == row.lockico || undefined == row.lockico) ? 0 : row.lockico);
                }
            },
            { label: 'GET/锁仓', name: 'eth', sortable:false, width: 80  , formatter: function(value, options, row)
                {
                    return ((null == row.eth || undefined == row.eth) ? 0 : row.eth) + "/" + ((null == row.locketh || undefined == row.locketh) ? 0 : row.locketh);
                }
            },
            { label: '合赢分', name: 'fen', sortable:false, width: 80 },
            { label: '贝壳/锁仓', name: 'cowry', sortable:false, width: 80 , formatter: function(value, options, row)
                {
                    return ((null == row.cowry || undefined == row.cowry) ? 0 : row.cowry) + "/" + ((null == row.lockcowry || undefined == row.lockcowry) ? 0 : row.lockcowry);
                }
            },
			{ label: '用户钱包地址', name: 'moneyAddress', sortable:false, width: 80 },
			{ label: '创建时间', name: 'timeCreate', sortable:false, width: 80 },
            { label: '操作', name: 'operation', sortable:false, width: 96, formatter: function(value, options, row)
            {
                var ret = "";
                if(hasPermission("fund:updateYtfAddress")){
                	if($.isEmptyObject(row.moneyAddress)){
                        ret  += "<a href='javascript:vm.updateYtfAddress(" + row.id +",\""+row.phone+"\");'><span class='label label-primary'><i class='fa fa-bitcoin'></i>创建钱包地址</span></a>&nbsp;&nbsp;"
                    }
                }

                return ret;
            }
            }
			//{ label: '更新时间', name: 'timeUpdate', sortable:false, width: 80 }
			// { label: '冻结金额', name: 'frozenMoney', sortable:false, width: 80 }
        ],
		viewrecords: true,
        height: 385,
        rowNum: 20,
		rowList : [10,20,30,50,100,200],
        rownumbers: false, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.pageNum",
            total: "page.pages",
            records: "page.total"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }

    });
    jQuery("#jqGrid").jqGrid('navGrid','#jqGrid',{edit:false,add:false,del:false});
    
    //过滤时间
    var rangetime = $('#filterTime').daterangepicker({
        autoApply:false,
        singleDatePicker:false,
        showDropdowns:true,         // 是否显示年月选择条件
    	timePicker: true, 			// 是否显示小时和分钟选择条件
    	timePickerIncrement: 10, 	// 时间的增量，单位为分钟
        timePicker24Hour : true,
        opens : 'left', //日期选择框的弹出位置
        startDate: moment().startOf('year'), //startDate和endDate 的值如果跟 ranges 的两个相同则自动选择ranges中的行. 这里选中了清空行
        endDate: moment().endOf('year'),
    	ranges: {
    		'今日': [moment().startOf('day'), moment().endOf('day')],
    		'昨日': [moment().subtract(1, 'days').startOf('day'), moment().subtract(1, 'days').endOf('day')],
    		'最近7日': [moment().subtract(6, 'days'), moment()],
    		'最近30日': [moment().subtract(29, 'days'), moment()],
    		'本月': [moment().startOf('month'), moment().endOf('month')],
    		'上个月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
    		'本年': [moment().startOf('year'), moment().endOf('year')],
    		'去年': [moment().subtract(1, 'year').startOf('year'), moment().subtract(1, 'year').endOf('year')]
    	},
        locale : {
            //format: 'YYYY-MM-DD HH:mm:ss',
            format: 'YYYY-MM-DD HH:mm',
            separator : ' - ',
        	customRangeLabel : '自定义',
            applyLabel : '确定',
            cancelLabel : '取消',
            fromLabel : '起始时间',
            toLabel : '结束时间',
            daysOfWeek : [ '日', '一', '二', '三', '四', '五', '六' ],
            monthNames : [ '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月' ],
            firstDay : 1,
            startDate: moment().startOf('day'),
            endDate: moment().endOf('day')
        }
    },
    function(start, end, label) // 格式化日期显示框
    {
    	//选择时间 回调，暂时不做操作。。。
        $('#filterTime').val(start.format('YYYY-MM-DD HH:mm') + " - " + end.format('YYYY-MM-DD HH:mm'));
    });
    
    $('#filterTime').val('');
    setTimeout("$('#filterTime').val('')", 100);
});


var vm = new Vue({
	el:'#rrapp',
	data:{
		q:{
			key: null
		},
		showList: true,
		title: null,
		dto: {}
	},
	methods: {
		query: function () {
			vm.reload();
		},
		trash: function () {
			$('#filterTime').val('');
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.dto = {};
		},
		transfer: function (event) {
			
//			var id = getSelectedRow();
//			if(id == null){
//				return ;
//			}
			var arr = new Array();
			vm.showList = false;
            vm.title = "转账";
			var url=baseURL + "user/list" ;
//         vm.getInfo(id);
            $.ajax({
				type: "GET",
			    url: url,
			   
			    success: function(r){
			        console.log(r);
                     for(var i=0;i<r["userPhone"].length;i++){
                    	 for(var j=0;j<r["userPhone"][i].length;j++){
                    	arr.push(r["userPhone"][i][j]);
                    	
                    	 }
                     }
                     
                     for(var i=0;i<arr.length;i++){
                    	 //动态创建下拉框列表
                    	
                    	$("#selectPhone").append("<option value="+arr[i]+">"+arr[i]+"</option>") ;
                    	
                    	$("#selectPhone").change(function(){
                    		if($("#selectPhone option:checked").val()!=""){
                    			var data=$("#selectPhone option:checked").val();
                    			getUserMoney(data);
                    		}
                    		
                    		
                    	});
                     }
                     
				}
			});
            
            
		},
		updMoney: function (id) {
			if(id == null){
				return ;
			}
			var ids = [id];
			confirm('确定要修改余额？', function(){
				$.ajax({
					type: "PUT",
				    url: baseURL + "",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code === 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		saveOrUpdate: function (event) {
			
			 var parms={};
			 parms.fromAccount=$("#selectPhone option:checked").val();
			 parms.accountMoney=$("#transAmount").val();
			
			 parms.toPhone=$("#toPhone").val();
			 parms.toAmount= $("#amount").val();
		   
			var url=baseURL + "user/transferBehind" ;
			
			$.ajax({
				type: "POST",
			    url: url,
			    data: JSON.stringify(parms),    
			    success: function(r){
			    	  
//                     for(var i=0;i<r["userPhone"].length;i++){
//                    	 for(var j=0;j<r["userPhone"][i].length;j++){
//                    	var result= r["userPhone"][i][j];
//                    	 }
//                    	 
//                     }    
//			    	if(r.code === 0){
//						alert('操作成功', function(index){
//							vm.reload();
//						});
//					}else{
//						alert(r.msg);
//					}
				}
			});
		},
		delCol: function (id) {
			if(id == null){
				return ;
			}
			var ids = [id];
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "PUT",
				    url: baseURL + "fund/delete",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code === 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "PUT",
				    url: baseURL + "fund/delete",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code === 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			console.log(1)
			$.get(baseURL + "fund/info/"+id, function(r){
                vm.dto = r.dto;
            });
		},
		reload: function (event) {
			vm.showList = true;

			var _postData = $("#jqGrid").jqGrid('getGridParam','postData');
			delete _postData['sts'];
			delete _postData['ets'];
			delete _postData['p'];
			
			_postData['p'] = $("#phoneAccount").val();
            _postData['ytfType'] = $("#ytfType").val();
            _postData['money'] = $("#money").val();
            _postData['equalsf'] = $("#equalsf").val();
			if((vtime = $.trim($('#filterTime').val())) != '')
			{
				if(vtime.indexOf(" - ") > -1)
				{
					_postData['sts'] = ($.trim(vtime.split(" - ")[0]) + ":00");
					_postData['ets'] = ($.trim(vtime.split(" - ")[1]) + ":59");
				}
				else
				{
					_postData['sts'] = getTime(vtime);
				}
			}
			
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page
            }).trigger("reloadGrid");
		},
        updateBatchAddress : function (event) {
            confirm('确认要批量创建钱包地址？', function(){
                $.ajax({
                    type: "PUT",
                    url: baseURL + "fund/updateBatchAddress",
                    data: null,
                    success: function(r){
                        if(r.code === 0){
                            alert('操作成功', function(index){
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        updateYtfAddress:function(id,phone){ //以太坊地址为空，生成地址
            if(id == null || phone == null){
                return;
            }
            confirm('确认要创建用户钱包地址？', function(){
                $.ajax({
                    type: "PUT",
                    url: baseURL + "fund/updateYtfAddress",
                    data: JSON.stringify({"id" : id,"phone" : phone}),
					async: false,
                    success: function(r){
                        if(r.code === 0){
                            alert('操作成功', function(index){
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
        }
		
	}
	
	
});

function getUserMoney(data){
	
	$.ajax({
		type: "GET",
		url:baseURL+"user/showMoney?phone="+data,
		success:function(r){
			
			console.log(r.fundEntity["money"]);
			var money=r.fundEntity["money"];
			var frozen=r.fundEntity["frozenMoney"];
			$("#transAmount").val(money-frozen);
			
			
		}
		
		
	})
	
}